package com.sam.java;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * BlockingQueue
 * 入队->容量满时 add-抛异常 offer-返回false put阻塞 offer(o,time,unit) 阻塞到超时
 * 出队->容量满时 remove-抛异常 poll-返回false take阻塞 poll(o,time,unit) 阻塞到超时
 * Created by samwang on 2018/4/22.
 */
public class ProducerConsumerBlockQueue {
    public static void main(String[] args) {
        Storage storage = new Storage();

        new Thread(){
            @Override
            public void run() {
                try {
                    while (storage.optionCount > 0) {
                        storage.produce();
                    }
                    storage.quit();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                try {
                    while (storage.optionCount > 0) {
                        storage.consume();
                    }
                    storage.quit();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }


    static class Storage {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
        Random random = new Random();

        int optionCount = 50;//操作完结束

        public void produce() throws InterruptedException {
            queue.put(1);
            System.out.println("produce one , current  " + queue.size());
            Thread.sleep(getRandomTime());
            optionCount--;
        }

        public void consume() throws InterruptedException {
            queue.take();
            System.out.println("consume one , current  " + queue.size());
            Thread.sleep(getRandomTime() * 2);//slow consume
            optionCount--;
        }

        public void quit() throws InterruptedException {
                if (queue.size() == 10) {
                    consume();

                } else if (queue.size() == 0) {
                    produce();
                }
        }

        public int getRandomTime() {
            return random.nextInt(200);
        }
    }
}
